// page/recommend/recommend.js
import request from "../../utils/request";
import PubSub from 'pubsub-js';

let innerAudioContext = null;
let pid = '';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        day: 1,
        mouth: 5,
        recommendList: [],
        playId: '',
        index: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            day: new Date().getUTCDay(),
            mouth: new Date().getUTCMonth() + 1
        });
        this.getRecommendList();
        PubSub.subscribe("switchType", (id, data) => {
                // 上一首
                let playId = '';
                let index = this.data.index;
                if (data === "pre") {
                    this.setData({
                        index: index === 0 ? index = 29 : --index
                    });
                    playId = this.data.recommendList[this.data.index].id;
                    this.setData({
                        playId
                    })
                    // 下一首
                } else {
                    this.setData({
                        index: index === 29 ? index = 0 : ++index
                    });
                    playId = this.data.recommendList[this.data.index].id;
                    this.setData({
                        playId
                    })
                }
                PubSub.publish("musicId", playId)
            }
        )
    },
    // 播放歌曲
    async playSong(event) {
        this.setData({
            playId: event.currentTarget.id
        });
        let index = event.currentTarget.dataset.index;
        this.setData({
            index
        });
        pid = event.currentTarget.id;
        wx.navigateTo({
            url: '/page/songDetail/songDetail?musicId=' + pid
        })
    },
    async getRecommendList() {
        let recommendData = await request("/recommend/songs");
        let recommendList = recommendData.recommend.splice(0, 30);
        let index = 0;
        recommendList = recommendList.map(item => {
            item.index = index++;
            return item;
        });
        this.setData({
            recommendList
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
